class Solution 
{
public:

    //烂橘子就是烂橘子，它能变好？
    //黑犀铠甲，合体！

    int row, col;
    int dx[4] = {0, 0, 1, -1};
    int dy[4] = {1, -1, 0, 0};

    int orangesRotting(vector<vector<int>>& grid) 
    {
        row = grid.size(), col = grid[0].size();
        vector<vector<bool>> vvb(row, vector<bool>(col, false)); 

        queue<pair<int, int>> qpii;

        for(int i=0; i<row; ++i)
        {
            for(int j=0; j<col; ++j)
            {
                if(grid[i][j] == 2) qpii.push({i, j});
            }
        }
        
        int ret = 0;
        while(qpii.size())
        {
            int num = qpii.size();
            ++ret;

            while(num--)
            {
                auto [i, j] = qpii.front();
                qpii.pop();

                for(int k=0; k<4; ++k)
                {
                    int x = i + dx[k], y = j + dy[k];
                    if(x < 0 || x >= row || y < 0 || y >= col) continue;

                    if(grid[x][y] == 1 && vvb[x][y] == false)
                    {
                        vvb[x][y] = true;
                        qpii.push({x, y});
                    }
                }
            }
        }

        for(int i=0; i<row; ++i)
        {
            for(int j=0; j<col; ++j)
            {
                if(grid[i][j] == 1 && vvb[i][j] == false) return -1;
            }
        }

        return ret == 0 ? 0 : ret - 1;
    }
};